/* © 2007 Adobe Systems Incorporated. All rights reserved. */package com.shubhjai.musiclib.data{
	
import com.shubhjai.musiclib.commands.BatchSQLCommand;
import com.shubhjai.musiclib.commands.Command;
import com.shubhjai.musiclib.commands.SQLCommand;
import com.shubhjai.musiclib.events.CommandCompleteEvent;
import com.shubhjai.musiclib.managers.ConfigManager;

import flash.data.SQLResult;
import flash.errors.SQLError;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.net.Responder;
	/**
	 * This class is responsible for checking if the database needs initialization and 	 * initializing if necessary.
	 */ 
	public class InitDatabaseCommand extends SQLCommand
	{				private var databasePopulated : Boolean = false;				/**		 * Constructor.		 */ 		public function InitDatabaseCommand() 		{		}		
		/**
		 * Execute the database initialization command.
		 */ 
		override protected function executeSQL() : void
		{			stmt.text = "select * from updatelog;";        	stmt.execute( -1, new Responder( onUpdateLogResult, dbInitRequired ) );		}				private function onUpdateLogResult( res:SQLResult ) : void		{			var version : String = res.data[0]["appVersion"];						var currentVersion : String = ConfigManager.getInstance().getProperty( "appVersion" );						if ( currentVersion != version )			{				logDebug( "Database app version out of date. Updating v" + version + " to v" + currentVersion );				initDB();			}			else			{					databasePopulated = true;				syncDB();			}		}				private function dbInitRequired( err:SQLError ) : void		{			logDebug("dbInitRequired()");			initDB();		}				private function initDB() : void		{			var currentVersion : String = ConfigManager.getInstance().getProperty( "appVersion" );			if ( currentVersion == null )			{				currentVersion = "0.0";			}			
			var batchExec : BatchSQLCommand = new BatchSQLCommand();			batchExec.addEventListener( CommandCompleteEvent.COMPLETE, onBatchExecComplete );			batchExec.addEventListener( ErrorEvent.ERROR, onBatchExecError );						batchExec.addStatement( "DROP INDEX IF EXISTS ind_empl_firstName;" );			batchExec.addStatement( "DROP INDEX IF EXISTS ind_empl_lastName;" );			batchExec.addStatement( "DROP INDEX IF EXISTS ind_empl_id;" );			batchExec.addStatement( "DROP INDEX IF EXISTS ind_empl_mgrId;" );			batchExec.addStatement( "DROP INDEX IF EXISTS ind_empl_dept;" );			batchExec.addStatement( "DROP TABLE IF EXISTS updatelog;" );			batchExec.addStatement( "DROP TABLE IF EXISTS employee;" );							// NOTE: lastUpdated will store the current time in milliseconds. But it *must* be TEXT or else it maxes out the integer storage			// of the DB.					// NOTE: We initialize to version 0.0 here, but when we first sync we will set to the current version			batchExec.addStatement( "CREATE TABLE updatelog( lastUpdated TEXT, appVersion TEXT );" );			batchExec.addStatement( "INSERT INTO updatelog VALUES ( '-1', '0.0' );" );						var stmtText : String = "CREATE TABLE employee( id TEXT, firstName TEXT, lastName TEXT, displayName TEXT, title TEXT, department TEXT" + 						", managerId TEXT, email TEXT, phone TEXT, phoneExtension TEXT, cellPhone TEXT, deskLocation TEXT, " + 						" location TEXT, city TEXT, state TEXT, postalCode TEXT, countryCode TEXT )";      				      		batchExec.addStatement( stmtText );      		      		batchExec.addStatement( "CREATE INDEX IF NOT EXISTS ind_empl_firstName ON employee (firstName);" );      		batchExec.addStatement( "CREATE INDEX IF NOT EXISTS ind_empl_lastName ON employee (lastName);" );      		batchExec.addStatement( "CREATE INDEX IF NOT EXISTS ind_empl_id ON employee (id);" );      		batchExec.addStatement( "CREATE INDEX IF NOT EXISTS ind_empl_mgrId ON employee (managerId);" );      		batchExec.addStatement( "CREATE INDEX IF NOT EXISTS ind_empl_dept ON employee (department);" );     		     		batchExec.execute();
		}
				private function onBatchExecComplete( evt:Event ) : void		{			var batchExec : BatchSQLCommand = evt.target as BatchSQLCommand;			batchExec.removeEventListener( CommandCompleteEvent.COMPLETE, onBatchExecComplete );			batchExec.removeEventListener( ErrorEvent.ERROR, onBatchExecError );			syncDB();		}				private function syncDB() : void		{			var syncCmd : SynchronizeDatabaseCommand = new SynchronizeDatabaseCommand();			syncCmd.addEventListener( CommandCompleteEvent.COMPLETE, onSyncComplete );			syncCmd.addEventListener( ErrorEvent.ERROR, onSyncError );			syncCmd.execute();
		}
						private function onSyncComplete( evt:Event ) : void		{			var syncCmd : SynchronizeDatabaseCommand = evt.target as SynchronizeDatabaseCommand;			syncCmd.removeEventListener( CommandCompleteEvent.COMPLETE, onSyncComplete );			syncCmd.removeEventListener( ErrorEvent.ERROR, onSyncError );			notifyComplete();		}						private function onBatchExecError( evt:ErrorEvent ) : void		{			var cmd : BatchSQLCommand = evt.target as BatchSQLCommand;			cmd.removeEventListener( CommandCompleteEvent.COMPLETE, onBatchExecComplete );			cmd.removeEventListener( ErrorEvent.ERROR, onBatchExecError );						dispatchEvent( evt.clone() );
		}				private function onSyncError( evt:ErrorEvent ) : void		{			logDebug( "onSyncError() populated: " + databasePopulated );			var syncCmd : SynchronizeDatabaseCommand = evt.target as SynchronizeDatabaseCommand;			syncCmd.removeEventListener( CommandCompleteEvent.COMPLETE, onSyncComplete );			syncCmd.removeEventListener( ErrorEvent.ERROR, onSyncError );									// We may be unconnected. Only fail if we don't have any data. 			if ( databasePopulated )					{				notifyComplete();				//ispatchEvent( evt );			}			else			{				dispatchEvent( evt.clone() );			}				}		
	}
}